package cc.angis.xiugallery;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.UUID;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import cc.angis.xiugallery.account.IAccountManager;
import cc.angis.xiugallery.account.QQWeiboAccountManager;
import cc.angis.xiugallery.account.WeiboAccountManager;
import cc.angis.xiugallery.common.GlobalConst;
import cc.angis.xiugallery.data.UserAccount;
import cc.angis.xiugallery.db.PostDBHelper;
import cc.angis.xiugallery.db.TableConstants;
import cc.angis.xiugallery.image.util.ImageResizer;
import cc.angis.xiugallery.provider.UserAccountProvider;
import cc.angis.xiugallery.util.NetworkStatus;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

public class ShareActivity extends SherlockActivity {
	
	private ImageView imageView;

	private EditText editText;

	private Button button;

	private long imgId;
	
	private UserAccountProvider provider;
	
	private String mImageData;
	
	private IAccountManager mAccountManager;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.weiboshare);
		ActionBar actiobar = getSupportActionBar();
		actiobar.setTitle(R.string.menu_sharetxt);
		actiobar.setDisplayHomeAsUpEnabled(true);
		imageView = (ImageView) findViewById(R.id.imageView);
		editText = (EditText) findViewById(R.id.postcontent);
		button = (Button) findViewById(R.id.send_button);

		imgId = getIntent().getLongExtra(GlobalConst.INTENT_IMAGE_ID, -1);
		new LoadImageTask(imageView).execute();
		
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (editText.getText() ==null || editText.getText().toString().equals("")){
					Toast.makeText(getApplicationContext(), R.string.toast_nocontent, Toast.LENGTH_SHORT).show();
					return;
				}
				if(NetworkStatus.getNetWorkStatus(getApplicationContext())==-1){
					Toast.makeText(getApplicationContext(), R.string.toast_nonetwork, Toast.LENGTH_SHORT).show();
					return;
				}
				
					
				if(provider.getUserAccounts() != null && provider.getUserAccounts().size() > 0){
					final String postId = UUID.randomUUID().toString();
					PostDBHelper dbHelper = new PostDBHelper(getApplicationContext(), TableConstants.TABLE_POST);
					try {
						dbHelper.insert(imgId, postId, editText.getText().toString(), Calendar.getInstance().getTimeInMillis(), 0);
					} catch(Exception e){
						
					} finally{
						dbHelper.closeDB();
					}
					IAccountManager accountManager;
					for (UserAccount account:provider.getUserAccounts()){
						switch (account.getType()){
							case GlobalConst.AccountType.ACCOUNT_TYPE_WEIBO:
								accountManager = new WeiboAccountManager(ShareActivity.this);
								accountManager.sharePic(account, postId, editText.getText().toString(), mImageData);
								break;
							case GlobalConst.AccountType.ACCOUNT_TYPE_QQ:
								mAccountManager = new QQWeiboAccountManager(ShareActivity.this);
								mAccountManager.sharePic(account, postId, editText.getText().toString(), mImageData);
								break;
							case GlobalConst.AccountType.ACCOUNT_TYPE_TWITTER:
								break;
							default:
								break;
						}
					}
				}else {
					Toast.makeText(getApplicationContext(), R.string.noaccountused, Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		provider = new UserAccountProvider(getApplicationContext());
		provider.initSource();
		
	}
	
	class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
		
		private ImageView imageView;
		
		public LoadImageTask(ImageView imageView){
			this.imageView = imageView;
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			try{
				String[] projection = new String[]{
			            MediaStore.Images.Media.DATA,
			            MediaStore.Images.Media.ORIENTATION,
			    };

			    // Get the base URI for the People table in the Contacts content provider.
			    Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

			    // Make the query.
			    Cursor cur = ShareActivity.this.getContentResolver().query(images,
			            projection, // Which columns to return
			            MediaStore.Images.Media._ID+ "=?",         // Which rows to return (all rows)
			            new String[]{String.valueOf(imgId)},       // Selection arguments (none)
			            null        // Ordering
			            );

			    Log.i("ListingImages"," query count="+cur.getCount());
			    String imageData = null;
			    int orientation = 0;
			    if (cur.moveToFirst()) {
			    	
			        int imageDataColumn = cur.getColumnIndex(
			            MediaStore.Images.Media.DATA);
			        int orientationColumn = cur.getColumnIndex(
			        		MediaStore.Images.Media.ORIENTATION);

			        do {
			            // Get the field values
			        	imageData = cur.getString(imageDataColumn);
			        	mImageData = imageData;
			        	orientation = cur.getInt(orientationColumn);
//			            Log.i("ListingImages", " bucket=" + bucket 
//			                   + "  date_taken=" + date);
			        } while (cur.moveToNext());

			    }
			    cur.close();
			    
			    Bitmap bitmap = ImageResizer.decodeSampledBitmapFromFile(imageData, 1280, 720, orientation);
			    //
			    String savePath = GlobalConst.PATH_PIC;
			    File file = new File(savePath);
			    if(!file.isDirectory())
			    	file.mkdirs();
			    mImageData = savePath + UUID.randomUUID().toString()+".png";
			    saveMyBitmap(bitmap, mImageData);
			    
			    return bitmap;
			    
	        }catch(Exception e){
	        	return null;
	        }
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			if (result != null)
				imageView.setImageBitmap(result);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			imageView.setImageResource(R.drawable.image_background);
		}
		
	}
	
	public void saveMyBitmap(Bitmap bitmap, String path) throws IOException {
        File f = new File(path);
        f.createNewFile();
        FileOutputStream fOut = null;
        try {
                fOut = new FileOutputStream(f);
        } catch (FileNotFoundException e) {
                e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.PNG, 80, fOut);
        try {
                fOut.flush();
        } catch (IOException e) {
                e.printStackTrace();
        }
        try {
                fOut.close();
        } catch (IOException e) {
                e.printStackTrace();
        }
}

	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)   {
        if (requestCode==1) {
            if (resultCode==OAuthV2AuthorizeWebView.RESULT_CODE)    {
            	if (mAccountManager !=null && mAccountManager instanceof QQWeiboAccountManager){
            		((QQWeiboAccountManager)mAccountManager).doAuth2((OAuthV2) data.getExtras().getSerializable("oauth"));
            	}
            }
        }
    }

}
